<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               :row-class-name="tableRowClassName"
               @sort-change="sortChange"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.member_cookbook_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-date-picker
          style="margin-right: 10px; width: 200px !important; height: 32px; line-height: 32px;"
          v-if="permission.member_cookbook_general"
          v-model="date"
          align="right"
          unlink-panels
          value-format="yyyy-MM-dd">
        </el-date-picker>
        <el-button type="warning"
                   size="small"
                   v-if="permission.member_cookbook_general"
                   plain
                   @click="handleRegeneral">重新生成订单
        </el-button>
        <el-button type="warning"
                   size="small"
                   plain
                   @click="handleChangeIsGeneralNo">修改为个性餐
        </el-button>
        <el-button type="primary"
                   size="small"
                   plain
                   @click="handleChangeIsGeneralYes">修改为标准餐
        </el-button>
        <el-tooltip class="item" effect="dark" content="系统默认每周五12时生成下周订单, 点击此按钮可重新生成下周订单" placement="top-start">
          <el-button type="danger"
                     size="small"
                     v-if="permission.member_cookbook_general"
                     plain
                     @click="handleGeneral">生成下周订单
          </el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="系统默认前一日晚上10时完成当日的订单，将订单状态修改为完成，并计算客服提成及需要补差价或反差价的记录" placement="top-start">
          <el-button type="success"
                     size="small"
                     plain
                     @click="handleComplete">完成订单
          </el-button>
        </el-tooltip>
        <el-switch
          v-model="showCancel"
          active-text="显示取消订单"
          @change="showCancelChange"
          inactive-text="">
        </el-switch>
      </template>
      <template slot="menu" slot-scope="{row}">
        <el-button size="small"
                   v-if="[1, 2].includes(row.status)"
                   type="text"
                   @click="handleCancel(row)">取 消
        </el-button>
      </template>
      <template slot="expand" slot-scope="{row}">
        <basic-container style="margin-left: 100px">
          <div>
            <span>{{ `菜品: ` }}</span>
            <el-tag :key="index" style="margin-right: 10px; margin-bottom: 10px" v-for="(item, index) in formatRowFood(row)">
              {{ item.foodName }}
            </el-tag>
          </div>
        </basic-container>
      </template>
      <template slot="search" slot-scope="{row,size}">
        <div class="el-form-item el-form-item--small avue-form__item--">
          <label class="el-form-item__label">时间范围：</label>
          <el-date-picker
            style="margin-right: 10px; width: 400px !important; height: 32px; line-height: 32px;"
            v-model="search.dateRange"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions">
          </el-date-picker>
        </div>
        <div class="el-col el-col-6 el-col-offset-0 el-col-xs-24 el-col-sm-12 el-col-md-6 avue-form__row"
             style="padding-left: 10px; padding-right: 10px;"
        >
          <div class="el-form-item el-form-item--small avue-form__item--">
            <label class="el-form-item__label" style="width: 80px;">类型：</label>
            <el-select v-model="search.isGeneral"
                       placeholder="标准餐或个性餐"
                       style="margin-right: 10px; width: 200px !important; height: 32px; line-height: 32px;"
                       clearable
            >
              <el-option
                v-for="item in isGeneralOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="el-col el-col-6 el-col-offset-0 el-col-xs-24 el-col-sm-12 el-col-md-6 avue-form__row"
             style="padding-left: 10px; padding-right: 10px;"
        >
          <div class="el-form-item el-form-item--small avue-form__item--">
            <label class="el-form-item__label" style="width: 80px;">地址：</label>
            <el-input v-model="search.address"
                       placeholder="地址"
                       style="margin-right: 10px; width: 200px !important; height: 32px; line-height: 32px;"
                       clearable
            ></el-input>
          </div>
        </div>
      </template>
      <template slot-scope="{row}"
                slot="timeRange">
        <el-tag v-if="row.timeRange && row.timeRange !== ''" type="primary">{{ row.timeRange.replace(',', ' ~ ') }}</el-tag>
        <el-tag v-else type="info">未配置</el-tag>
      </template>
      <template slot-scope="{row}"
                slot="mealName">
        <el-tag v-if="row.mealName && row.mealName !== '' && row.mealName.includes('中式')" type="warning">{{ row.mealName }}</el-tag>
        <el-tag v-else-if="row.mealName && row.mealName !== '' && row.mealName.includes('西式')" type="success">{{ row.mealName }}</el-tag>
        <el-tag v-else type="info">其他</el-tag>
      </template>
      <template slot-scope="{row}" slot="status">
        <el-tag v-if="row.status === 2" type="primary">已创建</el-tag>
        <el-tag v-else-if="(row.status === 3 || row.status === 4) && row.isTimeoutCancel === 1" type="danger">取消(超时)</el-tag>
        <el-tag v-else-if="(row.status === 3 || row.status === 4) && row.isTimeoutCancel === 2" type="danger">取消</el-tag>
        <el-tag v-else-if="row.status === 99" type="success">完成</el-tag>
        <el-tag v-else type="danger">未知</el-tag>
      </template>
      <template slot-scope="{row}" slot="deliveryStatus">
        <el-tag v-if="row.deliveryStatus === 0" type="primary">待配送</el-tag>
        <el-tag v-else-if="row.deliveryStatus === 1" type="warning">配送中</el-tag>
        <el-tag v-else-if="row.deliveryStatus === 99" type="success">配送完成</el-tag>
        <el-tag v-else type="danger">未知</el-tag>
      </template>
      <template slot-scope="{row}" slot="isGeneral">
        <el-tag v-if="row.isGeneral === 1" type="primary">标准餐</el-tag>
        <el-tag v-else-if="row.isGeneral === 2" type="warning">个性餐</el-tag>
        <el-tag v-else type="danger">未知</el-tag>
      </template>
      <template slot-scope="{row}" slot="memberName">
        <a class="el-link" style="color: #2d8cf0" @click="openDetail(row)">{{ row.memberName }}</a>
      </template>
    </avue-crud>
    <el-dialog title="详情"
               append-to-body
               :visible.sync="detailVisible"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               width="80%">
      <member-detail v-if="detailVisible" :id="memberId" :tab="4"></member-detail>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  add,
  cancel,
  changeIsGeneralNo,
  changeIsGeneralYes,
  complete,
  general,
  generalDate,
  getDetail,
  getList,
  remove,
  update
} from "@/api/member/member_cookbook";
import {mapGetters} from "vuex";
import {dateFormat} from "../../util/date";
import MemberDetail from "../member/member_detail";

const baseTop = 20

export default {
    components: { MemberDetail },
    data() {
      return {
        detailVisible: false,
        memberId: '',
        showCancel: false,
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 100,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height: 'auto',
          calcHeight: 210,
          searchShow: true,
          searchMenuSpan: 6,
          menuWidth: 100,
          expand: true,
          tip: false,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          refreshBtn: false,
          columnBtn: false,
          column: [
            {
              label: "会员",
              prop: "memberName",
              search: true,
              slot: true,
            },
            // {
            //   label: "编号",
            //   prop: "code",
            //   width: '160px',
            //   search: true,
            //   overHidden: true,
            // },
            {
              label: "门店",
              prop: "merchantId",
              type: "select",
              dicUrl: '/api/merchant/merchant/select',
              search: true,
              props: {
                label: "name",
                value: "id"
              },
            },
            {
              label: "收件人",
              prop: "receiver",
              slot: true,
              overHidden: true,
            },
            {
              label: "电话",
              prop: "telephone",
              width: '100px',
            },
            {
              label: "地址",
              prop: "address",
              width: '200px',
              overHidden: true,
            },
            {
              label: "送达时间",
              prop: "timeRange",
              row: true,
              slot: true,
              span: 24,
            },
            {
              label: "门牌",
              prop: "addressDetail",
              width: '200px',
              overHidden: true,
            },
            {
              label: "日期",
              prop: "date",
              width: '100px',
            },
            {
              label: "餐型",
              prop: "mealName",
              slot: true
            },
            {
              label: "类型",
              slot: true,
              prop: "isGeneral",
            },
            {
              label: "状态",
              prop: "status",
              slot: true,
            },
            {
              label: "主食类型",
              prop: "mainCourseType",
              sortable: 'custom',
              width: '100px',
            },
            {
              label: "备注",
              prop: "remark",
              search: true,
              sortable: 'custom',
              overHidden: true,
            },
            {
              label: "其他备注",
              prop: "remark1",
              sortable: 'custom',
              overHidden: true,
              width: '100px',
            },
            {
              label: "创建时间",
              prop: "createTime",
              overHidden: true,
            },
            {
              label: "最后更新时间",
              prop: "updateTime",
              overHidden: true,
              sortable: 'custom',
              display: false,
              width: '120px',
            },
          ]
        },
        data: [],
        search: {
          dateRange: '',
          address: '',
          isGeneral: '',
        },
        isGeneralOptions: [
          {
            value: '1',
            label: '标准餐'
          }, {
            value: '2',
            label: '个性餐'
          }
        ],
        mealOptions: [
          {
            value: '1',
            label: 'A餐'
          }, {
            value: '2',
            label: 'B餐'
          }
        ],
        pickerOptions: {
          shortcuts: [
            {
              text: '今日',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '明日',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() + 3600 * 1000 * 24);
                end.setTime(end.getTime() + 3600 * 1000 * 24);
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '昨日',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24);
                end.setTime(end.getTime() - 3600 * 1000 * 24);
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '最近一周',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit('pick', [start, end]);
              }
            }, {
              text: '最近一个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit('pick', [start, end]);
              }
            }, {
              text: '最近三个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit('pick', [start, end]);
              }
            }]
        },
        orderMainCourseType: '',
        orderRemark: '',
        orderRemark1: '',
        orderUpdateTime: '',
        date: '',
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.member_cookbook_add, false),
          viewBtn: this.vaildData(this.permission.member_cookbook_view, false),
          delBtn: this.vaildData(this.permission.member_cookbook_delete, false),
          editBtn: this.vaildData(this.permission.member_cookbook_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      },
      formatRowFood() {
        return (row) => {
          try {
            return JSON.parse(row.foods)
          } catch (e) {
            return {}
          }
        }
      },
    },
    created() {
      const now = new Date()
      now.setTime(now.getTime() + 3600 * 1000 * 24)
      this.search.dateRange = [
        dateFormat(now),
        dateFormat(now)
      ]

    },
    methods: {
      openDetail(row) {
        this.memberId = row.memberId
        this.detailVisible = true
      },
      tableRowClassName ({ row, rowIndex }) {
        if (row.firstDay === 1) {
          return 'success-row';
        }
        return '';
      },
      sortChange(column) {
        this.orderRemark = ''
        this.orderRemark1 = ''
        this.orderMainCourseType = ''
        this.orderUpdateTime = ''

        let order = ''
        switch (column.order) {
          case 'ascending':
            order = 'ASC'
            break;
          case 'descending':
            order = 'DESC'
            break;
          default:
            order = ''
            break
        }

        if (column.prop === 'remark') {
          this.orderRemark = order
        } else if (column.prop === 'remark1') {
          this.orderRemark1 = order
        } else if (column.prop === 'mainCourseType') {
          this.orderMainCourseType = order
        } else if (column.prop === 'updateTime') {
          this.orderUpdateTime = order
        }
        this.onLoad(this.page)
      },
      showCancelChange() {
        this.onLoad(this.page)
      },
      handleGeneral() {
        this.$confirm("确定生成下周订单?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return general();
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleRegeneral() {
        if (this.date === '') {
          this.$message.warning('请选择重新生成的日期')
          return
        }
        this.$confirm("确定重新生成当日订单?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return generalDate(this.date);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleComplete() {
        if (!this.search.dateRange || this.search.dateRange === '') {
          this.$message.warning('请先选择日期')
          return
        }
        this.$confirm("确定完成今日订单?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return complete(this.search.dateRange[0]);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleCancel(row) {
        this.$confirm("确定取消订单?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return cancel(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      handleChangeIsGeneralNo() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据修改为个性餐?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return changeIsGeneralNo(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      handleChangeIsGeneralYes() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据修改为标准餐?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return changeIsGeneralYes(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.search.dateRange = ''
        this.search.isGeneral = ''
        this.search.meal = ''
        this.search.address = ''
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      onLoad(page, params = {}) {
        this.loading = true;
        if (this.search.dateRange && this.search.dateRange !== '') {
          params.startDate = this.search.dateRange[0]
          params.endDate = this.search.dateRange[1]
        }
        if (this.orderRemark && this.orderRemark !== '') {
          params.orderRemark = this.orderRemark
        }
        if (this.orderRemark1 && this.orderRemark1 !== '') {
          params.orderRemark1 = this.orderRemark1
        }
        if (this.orderMainCourseType && this.orderMainCourseType !== '') {
          params.orderMainCourseType = this.orderMainCourseType
        }
        if (this.orderUpdateTime && this.orderUpdateTime !== '') {
          params.orderUpdateTime = this.orderUpdateTime
        }
        if (this.search.isGeneral && this.search.isGeneral !== '') {
          params.isGeneral = this.search.isGeneral
        }
        if (this.search.meal && this.search.meal !== '') {
          params.meal = this.search.meal
        }
        if (this.search.address && this.search.address !== '') {
          params.address = this.search.address
        }
        params.showCancel = this.showCancel
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
.el-form-item {
  margin-right: 20px;
}
.el-input__icon {
  height: auto;
}
.avue-crud .el-input__inner, .avue-form .el-input__inner {
  height: 32px;
}
.success-row{
  background-color: #b4e59e !important;
  color: #000000;
}
</style>
